//
//  StatusRetweetedView.swift
//  微博Swift
//
//  Created by  justinchou on 16/2/29.
//  Copyright © 2016年  justinchou. All rights reserved.
//

import UIKit

/// 被转发微博 －Cell的子视图
class StatusRetweetedView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 私有控件
    /// 被转发的微博文字
    private let retweetedLabel: UILabel = UILabel(title: "@微博:转发文", fontSize: 14)
    /// 配图视图 - 被转发微博如果有图片，原创微博没有图片
    private let picturesView: StatusPicturesView = StatusPicturesView()
    /// 布局信息
    private let layout = StatusCellViewLayout()
    
    var viewModel: StatusViewModel? {
        didSet {
            
            retweetedLabel.text = viewModel?.retwteedText
            retweetedLabel.textAlignment = .Left
            
            //没有被转发的微博
            if viewModel?.status.retweeted_status == nil {
                retweetedLabel.snp_updateConstraints(closure: { (make) -> Void in
                    make.top.equalTo(self)
                })
                picturesView.snp_updateConstraints(closure: { (make) -> Void in
                    make.top.equalTo(retweetedLabel.snp_bottom)
                    make.size.equalTo(CGSizeZero)
                    make.bottom.equalTo(self)
                })
                
                return
            }
            
            // 有被转发微博
            retweetedLabel.snp_updateConstraints(closure: { (make) -> Void in
                make.top.equalTo(self).offset(layout.margin)
            })
            
            // 更新约束
            let offset = (viewModel?.retweetedPictureViewSize == CGSizeZero) ? 0 : layout.margin
            picturesView.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(viewModel!.retweetedPictureViewSize)
                make.top.equalTo(retweetedLabel.snp_bottom).offset(offset)
                
                make.bottom.equalTo(self).offset(-layout.margin)
            }
            picturesView.pic_urls = viewModel?.status.retweeted_status?.pic_urls
        }
    }
    
}

// MARK: - 设置界面布局
extension StatusRetweetedView {
    
    private func setupUI() {
        
        backgroundColor = superview?.backgroundColor
        
        // 1. 添加控件
        addSubview(retweetedLabel)
        addSubview(picturesView)
        
        // 2. 自动布局
        retweetedLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self).offset(layout.margin)
            make.right.equalTo(self).offset(-layout.margin)
            make.top.equalTo(self).offset(layout.margin)
        }
        picturesView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(retweetedLabel)
            make.top.equalTo(retweetedLabel.snp_bottom).offset(layout.margin)
            
            make.bottom.equalTo(self).offset(-layout.margin)
        }
    }
}
